import { NextResponse } from "next/server";
import { createDeepSeek } from "@ai-sdk/deepseek";
import { streamText } from "ai";
import type { Message } from "ai";

const validModels = new Set(["deepseek-v3", "deepseek-r1"]);

export const dynamic = "force-dynamic";

const deepseek = createDeepSeek({
  apiKey: process.env.DEEPSEEK_API_KEY,
  baseURL: process.env.BASE_URL,
});

export async function POST(req: Request) {
  try {
    // 验证环境变量
    if (!process.env.DEEPSEEK_API_KEY || !process.env.BASE_URL) {
      return NextResponse.json({ error: "服务配置错误" }, { status: 500 });
    }

    let requestBody;
    try {
      requestBody = await req.json();
    } catch (error) {
      return NextResponse.json({ error: "无效的请求格式" }, { status: 400 });
    }

    const { messages, model, temperature } = requestBody;

    // 验证请求参数
    if (!Array.isArray(messages)) {
      return NextResponse.json({ error: "无效的消息格式" }, { status: 400 });
    }

    if (model && !validModels.has(model)) {
      return NextResponse.json({ error: "不支持的模型类型" }, { status: 400 });
    }

    // 处理流式响应
    const result = await streamText({
      model: deepseek(model || "deepseek-v3"),
      system: "你是一个乐于助人的助手，使用简体中文回答",
      messages: messages as Message[],
      temperature: temperature ?? 0.7,
      maxTokens: 1024,
    });

    // 转换响应流
    // const stream = result.toDataStream({
    //   onStart: async () => {
    //     console.log('Stream started for model:', model);
    //   },
    //   onFinal: async (completion) => {
    //     console.log('Stream completed:', completion.substring(0, 50));
    //   },
    // });
    const stream = result.toDataStream();

    return new Response(stream, {
      headers: {
        "Content-Type": "text/event-stream",
        "Cache-Control": "no-cache",
        Connection: "keep-alive",
        "X-Content-Type-Options": "nosniff",
      },
    });
  } catch (error: any) {
    console.error("API Error:", error);

    // 分类错误处理
    const statusCode = error.status || 500;
    const errorMessage = error.message.includes("401")
      ? "API 认证失败"
      : error.message.includes("404")
      ? "请求资源不存在"
      : "服务暂时不可用";

    return NextResponse.json(
      {
        error: errorMessage,
        details:
          process.env.NODE_ENV === "development" ? error.message : undefined,
      },
      {
        status: statusCode,
        headers: {
          "Cache-Control": "no-store",
        },
      }
    );
  }
}
